package cn.codewen.shop.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {



    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 得到uri地址
        String uri = req.getRequestURI();
        //2. 分割得到/最后1部分值
        String m = uri.substring(uri.lastIndexOf("/")+1);
        //resp.getWriter().write(m);
        //3. 反射
        try {
            //3.1 通过this拿到当前类中的方法名
            Method method = this.getClass().getDeclaredMethod(m, HttpServletRequest.class, HttpServletResponse.class);
            //3.2 反射调用方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            //3.3 设置状态码为404
            resp.setStatus(404);
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
